package com.mall.url;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

@Component("urlAccessDecisionManager")
public class UrlAccessDecisionManager implements AccessDecisionManager {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        Iterator<ConfigAttribute> iterator = collection.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute attribute = iterator.next();
            String permissionValue = attribute.getAttribute();
            if ("no".equals(permissionValue)) {
                throw new AccessDeniedException("未授权");
            }
            String username = (String)authentication.getPrincipal();
            String permissionStr = (String)redisTemplate.boundHashOps("permission").get(username);
            if (permissionStr == null) {
                throw new AccessDeniedException("token过期，请重新登录！");
            }
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, String.class);
            try {
                List<String> permissionList = objectMapper.readValue(permissionStr, javaType);
                for (String permission : permissionList) {
                    if (permission.equals(permissionValue)) {
                        return;
                    }
                }
                throw new AccessDeniedException("请联系管理员分配权限！");
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
